import pygame
from pygame.sprite import Sprite


class Ship(Sprite):
    # 飞船类移动常量
    MOVE_STATE = 0
    MOVE_RIGHT = 1
    MOVE_LEFT = 2
    MOVE_UP = 3
    MOVE_DOWN = 4

    def __init__(self, screen: object, settings: object) -> None:
        super().__init__()
        # 第一步 初始化飞船属性：
        # 1.加载飞船图片 2.获取屏幕外接矩形 3.获取飞船外接矩形
        self.settings = settings
        self.screen = screen
        self.image = pygame.image.load(self.settings.image_paths['ship']).convert_alpha()
        self.screen_rect = screen.get_rect()
        self.rect = self.image.get_rect()  # 飞船的外接矩形等于飞船图片的外接矩形

        # 第二步 初始化飞船位置，将飞船放在屏幕底部中央
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

        # 第三步 初始化飞船移动标志
        self.moving_right = False
        self.moving_left = False
        self.moving_up = False
        self.moving_down = False

    def update(self) -> None:
        """响应飞船移动"""
        if not any([self.moving_right, self.moving_left, self.moving_up, self.moving_down]):
            return

        move_actions = {
            Ship.MOVE_RIGHT: (1, 0, lambda: self.rect.right < self.screen_rect.right),
            Ship.MOVE_LEFT: (-1, 0, lambda: self.rect.left > self.screen_rect.left),
            Ship.MOVE_UP: (0, -1, lambda: self.rect.top > self.screen_rect.top),
            Ship.MOVE_DOWN: (0, 1, lambda: self.rect.bottom < self.screen_rect.bottom)
        }

        dx, dy, condition = move_actions.get(self.MOVE_STATE, (0, 0, lambda: False))
        if condition():
            speed = self.settings.other['ship_speed']
            self.rect.centerx += dx * speed
            self.rect.centery += dy * speed

    # 旧的实现方法，使用match语句
    # def update(self) -> None:
    #     """响应飞船移动"""
    #     match self.MOVE_STATE:
    #         case Ship.MOVE_RIGHT:
    #             if self.moving_right:
    #                 if self.rect.right < self.screen_rect.right:
    #                     self.rect.centerx += self.settings.other['ship_speed']
    #         case Ship.MOVE_LEFT:
    #             if self.moving_left:
    #                 if self.rect.left > self.screen_rect.left:
    #                     self.rect.centerx -= self.settings.other['ship_speed']
    #         case Ship.MOVE_UP:
    #             if self.moving_up:
    #                 if self.rect.top > self.screen_rect.top:
    #                     self.rect.centery -= self.settings.other['ship_speed']
    #         case Ship.MOVE_DOWN:
    #             if self.moving_down:
    #                 if self.rect.bottom < self.screen_rect.bottom:
    #                     self.rect.centery += self.settings.other['ship_speed']

    def draw(self) -> None:
        """绘制飞船"""
        self.screen.blit(self.image, self.rect)